package ms.unicorn.diagram.edit.parts;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import ms.unicorn.Element;
import ms.unicorn.UnicornService;
import ms.unicorn.diagram.edit.policies.EntityItemSemanticEditPolicy;
import ms.unicorn.diagram.providers.UnicornElementTypes;
import ms.unicorn.dsl.HintedSpecializationType;
import ms.unicorn.dsl.IFigureEx;
import ms.unicorn.dsl.ILanguageElement;
import ms.unicorn.dsl.LanguageRegistry;
import ms.unicorn.util.FigureUtil;
import ms.unicorn.util.NotificationService;
import ms.unicorn.util.ViewUtil;

import org.eclipse.draw2d.ConnectionAnchor;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.GridData;
import org.eclipse.draw2d.GridLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.RectangleFigure;
import org.eclipse.draw2d.Shape;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.gef.ConnectionEditPart;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.LayoutEditPolicy;
import org.eclipse.gef.editpolicies.NonResizableEditPolicy;
import org.eclipse.gef.requests.CreateRequest;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeNodeEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.gef.ui.figures.DefaultSizeNodeFigure;
import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.swt.graphics.Color;

/**
 * @generated
 */
public class EntityEditPart extends ShapeNodeEditPart {

	/**
	 * @generated
	 */
	public static final int VISUAL_ID = 2001;

	/**
	 * @generated
	 */
	protected IFigure contentPane;

	/**
	 * @generated
	 */
	protected IFigure primaryShape;

	/**
	 * @generated
	 */
	public EntityEditPart(View view) {
		super(view);
	}

	/**
	 * @generated NOT
	 */
	protected void createDefaultEditPolicies() {
		super.createDefaultEditPolicies();
		installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE,
				new EntityItemSemanticEditPolicy());
		installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy());

		Element domainElement = (Element) resolveSemanticElement();
		ILanguageElement element = LanguageRegistry.INSTANCE
				.getLanguageElement(domainElement);
		if (element != null)
			element.createDefaultEditPolicies(this, domainElement);
		// XXX need an SCR to runtime to have another abstract superclass that would let children add reasonable editpolicies
		// removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE);
	}

	@Override
	public EditPolicy getPrimaryDragEditPolicy() {
		Element element = (Element) resolveSemanticElement();
		if (element != null) {
			ILanguageElement lang = LanguageRegistry.INSTANCE
					.getLanguageElement(element);
			if (lang != null) {
				EditPolicy policy = lang.createPrimaryDragEditPolicy(element,
						this);
				if (policy != null)
					return policy;
			}
		}
		return super.getPrimaryDragEditPolicy();
	}

	/**
	 * @generated
	 */
	protected LayoutEditPolicy createLayoutEditPolicy() {
		org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy lep = new org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy() {

			protected EditPolicy createChildEditPolicy(EditPart child) {
				EditPolicy result = child
						.getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE);
				if (result == null) {
					result = new NonResizableEditPolicy();
				}
				return result;
			}

			protected Command getMoveChildrenCommand(Request request) {
				return null;
			}

			protected Command getCreateCommand(CreateRequest request) {
				return null;
			}
		};
		return lep;
	}

	/**
	 * @generated
	 */
	protected IFigure createNodeShape() {
		return primaryShape = new EntityFigure();
	}

	/**
	 * @generated NOT
	 */
	public IFigure getPrimaryShape() {
		if (primaryShape == null && getFigure() != null) {
			primaryShape = FigureUtil.getChildFigure(getFigure(), IFigureEx.FLAG_CONNECTOR_ANCHOR);
		}
		return  primaryShape;
	}

	/**
	 * @generated NOT
	 */
	protected boolean addFixedChild(EditPart childEditPart) {
		if (childEditPart instanceof IFigureEditPart
				&& childEditPart.getModel() instanceof View) {
			View view = (View) childEditPart.getModel();
			String childViewName = ViewUtil.getViewName(view);
			IFigure figure = FigureUtil.getChildFigure(getFigure(),
					childViewName);
			if (figure != null) {
				((IFigureEditPart) childEditPart).setEditPartFigure(figure);
				return true;
			}
		}
		return false;
	}

	/**
	 * @generated NOT
	 */
	protected boolean removeFixedChild(EditPart childEditPart) {
		/*if (childEditPart instanceof EntityElementTypeEditPart) {
			return true;
		}
		if (childEditPart instanceof EntityNameTextEditPart) {
			return true;
		}*/
		if (childEditPart instanceof IFigureEditPart
				&& childEditPart.getModel() instanceof View) {
			View view = (View) childEditPart.getModel();
			String childViewName = ViewUtil.getViewName(view);
			IFigure figure = FigureUtil.getChildFigure(getFigure(),
					childViewName);
			if (figure != null)
				return true;
		}
		return false;
	}

	/**
	 * @generated
	 */
	protected void addChildVisual(EditPart childEditPart, int index) {
		if (addFixedChild(childEditPart)) {
			return;
		}
		super.addChildVisual(childEditPart, -1);
	}

	/**
	 * @generated
	 */
	protected void removeChildVisual(EditPart childEditPart) {
		if (removeFixedChild(childEditPart)) {
			return;
		}
		super.removeChildVisual(childEditPart);
	}

	/**
	 * @generated
	 */
	protected IFigure getContentPaneFor(IGraphicalEditPart editPart) {
		return getContentPane();
	}

	/** not use
	 * @generated
	 */
	protected NodeFigure createNodePlate() {
		DefaultSizeNodeFigure result = new DefaultSizeNodeFigure(40, 40);
		return result;
	}

	/**
	 * Creates figure for this edit part.
	 * 
	 * Body of this method does not depend on settings in generation model
	 * so you may safely remove <i>generated</i> tag and modify it.
	 * 
	 * @generated NOT
	 */
	protected NodeFigure createNodeFigure() {
		Element domainElement = (Element) resolveSemanticElement();
		ILanguageElement e = LanguageRegistry.INSTANCE
				.getLanguageElement(domainElement);
		if (e != null) {
			IFigure figure = e.createFigure(domainElement, this);

			if (figure instanceof NodeFigure)
				return (NodeFigure) figure;
		}
		return null;
	}

	/**
	 * Default implementation treats passed figure as content pane.
	 * Respects layout one may have set for generated figure.
	 * @param nodeShape instance of generated figure class
	 * @generated
	 */
	protected IFigure setupContentPane(IFigure nodeShape) {
		if (nodeShape.getLayoutManager() == null) {
			ConstrainedToolbarLayout layout = new ConstrainedToolbarLayout();
			layout.setSpacing(5);
			nodeShape.setLayoutManager(layout);
		}
		return nodeShape; // use nodeShape itself as contentPane
	}

	/**
	 * @generated
	 */
	public IFigure getContentPane() {
		if (contentPane != null) {
			return contentPane;
		}
		return super.getContentPane();
	}

	/**
	 * @generated
	 */
	protected void setForegroundColor(Color color) {
		if (primaryShape != null) {
			primaryShape.setForegroundColor(color);
		}
	}

	/**
	 * @generated
	 */
	protected void setBackgroundColor(Color color) {
		if (primaryShape != null) {
			primaryShape.setBackgroundColor(color);
		}
	}

	/**
	 * @generated
	 */
	protected void setLineWidth(int width) {
		if (primaryShape instanceof Shape) {
			((Shape) primaryShape).setLineWidth(width);
		}
	}

	/**
	 * @generated
	 */
	protected void setLineType(int style) {
		if (primaryShape instanceof Shape) {
			((Shape) primaryShape).setLineStyle(style);
		}
	}

	/**
	 * Return child editpart that will recieve focus.
	 * @generated NOT
	 */
	public EditPart getPrimaryChildEditPart() {
		View thisView = (View) this.getModel(); //(View) getViewer().getEditPartRegistry().get(this);
		View childView = ViewUtil.getChildView(thisView,
				ViewUtil.VIEW_PRIMARY_CHILD);
		if (childView != null)
			return (EditPart) this.getViewer().getEditPartRegistry()
					.get(childView);
		return null;
	}

	private static final List<IElementType> EMPTY_LIST = new ArrayList<IElementType>(
			0);

	/**
	 * @generated NOT
	 */
	public List<IElementType> getMARelTypesOnSource() {
		//ArrayList<IElementType> types = new ArrayList<IElementType>(1);
		//types.add(UnicornElementTypes.Relation_4001);
		//return types;
		Element domainElement = (Element) resolveSemanticElement();
		ILanguageElement e = LanguageRegistry.INSTANCE
				.getLanguageElement(domainElement);
		if (e != null)
			return e.getMARelTypesOnSource(this);
		return EMPTY_LIST;
	}

	/**
	 * @generated NOT
	 */
	public List<IElementType> getMARelTypesOnSourceAndTarget(
			IGraphicalEditPart targetEditPart) {
		/*LinkedList<IElementType> types = new LinkedList<IElementType>();
		if (targetEditPart instanceof ms.unicorn.diagram.edit.parts.EntityEditPart) {
			types.add(UnicornElementTypes.Relation_4001);
		}*/
		Element domainElement = (Element) resolveSemanticElement();
		ILanguageElement e = LanguageRegistry.INSTANCE
				.getLanguageElement(domainElement);
		if (e != null) {
			Element tarElement = (Element) targetEditPart
					.resolveSemanticElement();
			ILanguageElement tar = LanguageRegistry.INSTANCE
					.getLanguageElement(tarElement);
			return e.getMARelTypesOnSourceAndTarget(this, targetEditPart, tar);
		}
		return EMPTY_LIST;
	}

	/**
	 * @generated NOT
	 */
	public List<IElementType> getMATypesForTarget(IElementType relationshipType) {
		/*LinkedList<IElementType> types = new LinkedList<IElementType>();
		if (relationshipType == UnicornElementTypes.Relation_4001) {
			types.add(UnicornElementTypes.Entity_2001);
		}*/
		Element domainElement = (Element) resolveSemanticElement();
		ILanguageElement e = LanguageRegistry.INSTANCE
				.getLanguageElement(domainElement);
		if (e != null && relationshipType instanceof HintedSpecializationType)
			return e.getMATypesForTarget(this,
					(HintedSpecializationType) relationshipType);
		return EMPTY_LIST;
	}

	/**
	 * @generated NOT
	 */
	public List<IElementType> getMARelTypesOnTarget() {
		//ArrayList<IElementType> types = new ArrayList<IElementType>(1);
		//types.add(UnicornElementTypes.Relation_4001);
		Element domainElement = (Element) resolveSemanticElement();
		ILanguageElement e = LanguageRegistry.INSTANCE
				.getLanguageElement(domainElement);
		if (e != null)
			return e.getMARelTypesOnTarget(this);
		return EMPTY_LIST;
	}

	/**
	 * @generated NOT
	 */
	public List<IElementType> getMATypesForSource(IElementType relationshipType) {
		LinkedList<IElementType> types = new LinkedList<IElementType>();
		if (relationshipType == UnicornElementTypes.Relation_4001) {
			types.add(UnicornElementTypes.Entity_2001);
		}
		return types;
	}
	
	@Override
	public ConnectionAnchor getSourceConnectionAnchor(
			ConnectionEditPart connEditPart) {
		org.eclipse.gmf.runtime.diagram.ui.editparts.ConnectionEditPart connection = 
	            (org.eclipse.gmf.runtime.diagram.ui.editparts.ConnectionEditPart)connEditPart;
		return super.getSourceConnectionAnchor(connEditPart);
	}

	@Override
	protected void handleNotificationEvent(Notification notification) {
		super.handleNotificationEvent(notification);
		UnicornService.getNotificationService().dispatch(this,
				NotificationService.CHANNEL_EDITPART,
				notification.getEventType(), notification);
	}

	/**
	 * @generated
	 */
	public class EntityFigure extends RectangleFigure {

		/**
		 * @generated
		 */
		private WrappingLabel fFigureEntityNameFigure;
		/**
		 * @generated
		 */
		private WrappingLabel fFigureStereotypeFigure;

		/**
		 * @generated
		 */
		public EntityFigure() {

			GridLayout layoutThis = new GridLayout();
			layoutThis.numColumns = 1;
			layoutThis.makeColumnsEqualWidth = true;
			this.setLayoutManager(layoutThis);

			this.setLineStyle(Graphics.LINE_CUSTOM);
			createContents();
		}

		/**
		 * @generated
		 */
		private void createContents() {

			fFigureStereotypeFigure = new WrappingLabel();

			fFigureStereotypeFigure.setText("");

			GridData constraintFFigureStereotypeFigure = new GridData();
			constraintFFigureStereotypeFigure.verticalAlignment = GridData.CENTER;
			constraintFFigureStereotypeFigure.horizontalAlignment = GridData.CENTER;
			constraintFFigureStereotypeFigure.horizontalIndent = 0;
			constraintFFigureStereotypeFigure.horizontalSpan = 1;
			constraintFFigureStereotypeFigure.verticalSpan = 1;
			constraintFFigureStereotypeFigure.grabExcessHorizontalSpace = false;
			constraintFFigureStereotypeFigure.grabExcessVerticalSpace = false;
			this.add(fFigureStereotypeFigure, constraintFFigureStereotypeFigure);

			fFigureEntityNameFigure = new WrappingLabel();

			fFigureEntityNameFigure.setText("<...>");

			GridData constraintFFigureEntityNameFigure = new GridData();
			constraintFFigureEntityNameFigure.verticalAlignment = GridData.CENTER;
			constraintFFigureEntityNameFigure.horizontalAlignment = GridData.CENTER;
			constraintFFigureEntityNameFigure.horizontalIndent = 1;
			constraintFFigureEntityNameFigure.horizontalSpan = 1;
			constraintFFigureEntityNameFigure.verticalSpan = 1;
			constraintFFigureEntityNameFigure.grabExcessHorizontalSpace = false;
			constraintFFigureEntityNameFigure.grabExcessVerticalSpace = false;
			this.add(fFigureEntityNameFigure, constraintFFigureEntityNameFigure);

		}

		/**
		 * @generated
		 */
		public WrappingLabel getFigureEntityNameFigure() {
			return fFigureEntityNameFigure;
		}

		/**
		 * @generated
		 */
		public WrappingLabel getFigureStereotypeFigure() {
			return fFigureStereotypeFigure;
		}

	}

}
